package com.beverages.holder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beverages.holder.client.MerchantOrdersClient;
import com.beverages.holder.entity.Holder;
import com.beverages.holder.mapper.HolderMapper;
import com.beverages.holder.service.IHolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HolderServiceImpl extends ServiceImpl<HolderMapper, Holder> implements IHolderService {

    @Autowired
    private MerchantOrdersClient merchantOrdersClient;

    @Override
    public List<Holder> getUnusedHolders() {
        QueryWrapper<Holder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", 0);
        queryWrapper.eq("prepared_order_id", 0);
        queryWrapper.eq("processing_order_id", 0);
        queryWrapper.eq("waiting_order_id", 0);

        return this.list(queryWrapper);
//        return holderMapper.selectHolderWithZeroIds();
    }

    @Override
    public List<Holder> getHoldersWhichHavePreparedOrder(){
        QueryWrapper<Holder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", 0);
        queryWrapper.ne("prepared_order_id", 0);
        queryWrapper.eq("processing_order_id", 0);
        queryWrapper.eq("waiting_order_id", 0);

        return this.list(queryWrapper);
    }

    // 批量更新 prepared_order_id
    @Override
    public void updatePreparedOrderIds() {
        List<Holder> holders = getUnusedHolders();
        List<Integer> pendingOrdersIds = merchantOrdersClient.getPendingOrdersIds(holders.size()).getData();

        // 遍历 pendingOrdersIds 和 holders 进行逐条更新
        for (int i = 0; i < pendingOrdersIds.size(); i++) {
            if (i < holders.size()) {
                // 获取对应的 holder
                Holder holder = holders.get(i);

                // 设置 prepared_order_id
                holder.setPreparedOrderId(pendingOrdersIds.get(i));

                // 更新数据库
                updateById(holder);

                // 更改order表的制作状态
                merchantOrdersClient.updateCompletionStatus(pendingOrdersIds.get(i),1);
            }
        }
    }

}
